package cn.itcast.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;


@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER + 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {

        //获取请求上下文
        RequestContext ctx = RequestContext.getCurrentContext();
        //从上下文中取出requert
        HttpServletRequest request = ctx.getRequest();
        //从请求参数中获取 access-token
        String parameter = request.getParameter("access-token");
        //判断是否为空
        if (StringUtils.isBlank(parameter)){
            //为空，拦截
            ctx.setSendZuulResponse(false);
            //返回响应码
            ctx.setResponseStatusCode(401);//未授权
        }
        //不为空，放行
        return null;
    }
}
